/******************************************************************************
 * Copyright (C) 2015  671643387@qq.com
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *****************************************************************************/

#include "dump.h"
#include "string.h"

namespace pear {
    namespace util {

        void DumpSocketInputBuffer(::pear::net::Socket *sock, ::pear::log::Log *logger)
        {
            ::std::size_t data_size = sock->ReceiveSize();
            if (data_size > 0)
            {
                ::std::uint8_t *data = new ::std::uint8_t[data_size];
                if (data)
                {
                    ::std::size_t bytes_peek = sock->ReceivePeek(data, data_size);
                    if (bytes_peek > 0)
                    {
                        ::std::string message("\n");
                        while (bytes_peek > 0)
                        {
                            // print line
                            char line[0x80] = { 0 };
                            int line_idx = 0, line_i = 0;
                            int line_w = (bytes_peek > 16) ? 16 : bytes_peek;
                            for (; line_i < line_w; ++line_i)
                            {
                                int n = ::pear::util::String::snprintf(&line[line_idx],
                                    sizeof(line)-line_idx, "%02X ", data[line_i]);
                                if (n > 0) {
                                    line_idx += n;
                                    continue;
                                }
                                break;
                            }
                            line[line_idx] = '\n';
                            line[line_idx + 1] = '\0';
                            message.append(line);
                            bytes_peek -= line_i;
                        }

                        logger->log(message.c_str());
                    }

                    delete[] data;
                }
            }

        }

    }
}